package com.android.videotest;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.sansecy.android.simplevideo.Player;

import java.util.Formatter;
import java.util.Locale;

public class HorizontalControlView extends FrameLayout {

    private TextView mCurrentTime;
    private TextView mEndTime;
    private SeekBar mSeekBar;
    private ImageView mPlayButton;
    private View mFullScreen;
    private StringBuilder mFormatBuilder;
    private Formatter mFormatter;
    private Player mPlayer;
    private boolean mShowing;

    public HorizontalControlView(@NonNull Context context) {
        this(context, null);
    }

    public HorizontalControlView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(getContext()).inflate(R.layout.view_horizontal_video_control, this, true);

        mCurrentTime = findViewById(R.id.startTime);
        mEndTime = findViewById(R.id.endTime);

        mSeekBar = findViewById(R.id.seekBar);
        mSeekBar.setMax(1000);
        mSeekBar.setFocusable(false);
        mSeekBar.clearFocus();
        mFullScreen = findViewById(R.id.btn_full_screen);
        mPlayButton = findViewById(R.id.btn_play);
        mFormatBuilder = new StringBuilder();
        mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

        mFullScreen.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        mPlayButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayer.isPlaying()) {
                    mPlayer.pause();
                    mPlayButton.setImageResource(R.drawable.btn_play);
                } else {
                    mPlayer.start();
                    mPlayButton.setImageResource(R.drawable.btn_suspend);
                }
            }
        });
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {

                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                mPlayer.seekTo((int) (mPlayer.getDuration() * ((float) progress / seekBar.getMax())));
            }
        });
    }

    public void attachToVideoView(Player player) {
        mPlayer = player;
        post(mShowProgress);
        updatePausePlay();
        Log.d(this.getClass().getSimpleName() + "-App", "attachToVideoView: ");
    }

    public void start() {
        post(mShowProgress);
    }

    public void stop() {
        removeCallbacks(mShowProgress);
        updatePausePlay();
    }

    @Override
    public void onVisibilityAggregated(boolean isVisible) {
        super.onVisibilityAggregated(isVisible);
        mShowing = isVisible;
    }

    public void show() {
        mShowing = true;
        updatePausePlay();
    }

    public void hide() {
        mShowing = false;
        updatePausePlay();
    }

    public void updatePausePlay() {
        if (mPlayButton == null)
            return;
        if (mPlayer.isPlaying()) {
            mPlayButton.setImageResource(R.drawable.btn_suspend);
        } else {
            mPlayButton.setImageResource(R.drawable.btn_play);
        }
    }

    private static final String TAG = "HorizontalControlView-App";
    private final Runnable mShowProgress = new Runnable() {
        @Override
        public void run() {
            int pos = setProgress();
            if (mShowing) {
                postDelayed(mShowProgress, 1000 - (pos % 1000));
            }
        }
    };

    public int setProgress() {
        if (mPlayer == null) {
            return 0;
        }
        int position = mPlayer.getCurrentPosition();
        int duration = mPlayer.getDuration();
        if (mSeekBar != null) {
            if (duration > 0) {
                // use long to avoid overflow
                long pos = 1000L * position / duration;
                mSeekBar.setProgress((int) pos);
            }
            int percent = mPlayer.getBufferPercentage();
            mSeekBar.setSecondaryProgress(percent * 10);
        }
        Log.d(this.getClass().getName(), "setProgress: " + position / 1000);
        if (mEndTime != null)
            mEndTime.setText(stringForTime(duration));
        if (mCurrentTime != null)
            mCurrentTime.setText(stringForTime(position));

        return position;
    }

    private String stringForTime(int timeMs) {
        int totalSeconds = timeMs / 1000;

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        mFormatBuilder.setLength(0);
        if (hours > 0) {
            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }
}
